import { createRouter, createWebHistory } from "vue-router";
import store from "../store";
import { getCookie } from "../utils";
// import routesList from "./routes";

const routes = [
  // 登录
  {
    path: "/login",
    name: "login",
    meta: {
      title: "登录",
    },
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/login/index.vue"),
  },
  // 注册
  {
    path: "/register",
    name: "register",
    meta: {
      title: "注册",
    },
    component: () =>
      import(
        /* webpackChunkName: "register" */ "../views/login/register/index.vue"
      ),
  },
  // 协同编辑
  {
    path: "/article/amEditor",
    name: "articleAmEditor",
    meta: {
      title: "协同编辑",
      auth: ["访客"],
    },
    component: () =>
      import(
        /* webpackChunkName: "tags" */ "../views/home/article/amEditor/index.vue"
      ),
  },
  // 新建文章
  {
    path: "/article/editor",
    name: "articleEditor",
    meta: {
      title: "新建文章",
      auth: ["访客"],
    },
    component: () =>
      import(
        /* webpackChunkName: "tags" */ "../views/home/article/editor/index.vue"
      ),
  },
  // 新建页面
  {
    path: "/page/editor",
    name: "pageEditor",
    meta: {
      title: "新建文章",
      auth: ["访客"],
    },
    component: () =>
      import(
        /* webpackChunkName: "tags" */ "../views/home/page/editor/index.vue"
      ),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

const whiteList = ["/login", "/register"];

// 路由拦截
router.beforeEach((to, from, next) => {
  document.title = to.meta.title;

  if (whiteList.includes(to.path)) {
    next();
  } else {
    if (getCookie()) {
      if (store.state.routesList.length <= 0) {
        store.dispatch("getRoutes", store.state.userInfo.auth);

        next({ ...to, replace: true });
      }

      next();
    } else {
      next("/login");
    }
  }
});

export default router;
